<template>
  <div class="list-wrap">
    <a-typography-title class="block-title" :heading="6">
      Rule Setting
    </a-typography-title>
    <a-select
      v-model="selectedIndustry"
      placeholder="Select Industry"
      style="width: 200px; margin-bottom: 20px"
      @change="handleIndustryChange"
    >
      <a-option
        v-for="industry in industries"
        :key="industry.id"
        :value="industry.id"
      >
        {{ industry.industry_name }}
      </a-option>
    </a-select>
    <a-row class="list-row" :gutter="24">
      <a-col
        :xs="12"
        :sm="12"
        :md="12"
        :lg="6"
        :xl="6"
        :xxl="6"
        class="list-col"
        style="min-height: 200px"
      >
        <div class="card-wrap empty-wrap" @click="handleAddClick">
          <a-card :bordered="true" hoverable>
            <a-result :status="null" :title="'Click to Add New Rule'">
              <template #icon>
                <icon-plus style="font-size: 30px" />
              </template>
            </a-result>
          </a-card>
        </div>
      </a-col>

      <a-col
        v-for="item in filteredRules"
        :key="item.id"
        :xs="12"
        :sm="12"
        :md="12"
        :lg="6"
        :xl="6"
        :xxl="6"
        class="list-col"
        style="min-height: 200px"
      >
        <CardWrap
          :loading="loading"
          :title="item.name"
          :description="item.category"
          :expires-text="item.priority"
          :default-value="selectedRules.includes(item.id)"
          :tag-text="$t('cardList.preset.tag')"
          @card-click="handleCardClick(item)"
          @switch-click="handleSwitchClick(item)"
        >
          <template #skeleton>
            <a-skeleton :animation="true">
              <a-skeleton-line :widths="['100%', '100%']" :rows="2" />
              <a-skeleton-line :widths="['100%']" :rows="1" />
            </a-skeleton>
          </template>
        </CardWrap>
      </a-col>
    </a-row>
    <a-modal
      v-model:visible="isModalVisible"
      title="Rule Details"
      :width="1000"
      :centered="true"
      :mask-closable="true"
      :closable="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="rule-details">
        <div v-if="selectedRule.id !== 0">
          <strong>ID:</strong>
          <a-input v-model="selectedRuleId" placeholder="Enter rule ID" />
        </div>
        <div
          ><strong>Name:</strong>
          <a-input v-model="selectedRule.name" placeholder="Enter rule name"
        /></div>
        <div
          ><strong>Comment:</strong>
          <a-input
            v-model="selectedRule.comment"
            placeholder="Enter Your Comment"
        /></div>
        <div
          ><strong>description:</strong>
          <a-textarea
            v-model="selectedRule.description"
            placeholder="Enter Your description"
        /></div>

        <div
          ><strong>Category:</strong>
          <a-input
            v-model="selectedRule.category"
            placeholder="Enter category name"
        /></div>
        <div
          ><strong>Trigger Condition:</strong>
          <a-tooltip content="Default is True, execute rule anyway">
            <a-button shape="round" size="mini">? </a-button>
          </a-tooltip>
          <a-input
            v-model="selectedRule.trigger_condition"
            placeholder="Enter trigger condition"
        /></div>
        <div
          ><strong>Required Columns:</strong>
          <div
            v-for="(column, index) in selectedRule.required_columns"
            :key="index"
            class="required-column"
          >
            <a-input
              v-model="selectedRule.required_columns[index]"
              placeholder="Enter required column"
            />
            <a-button type="text" @click="removeRequiredColumn(index)">
              <icon-delete />
            </a-button>
          </div>

          <a-button @click="addRequiredColumn">Add Column</a-button>
        </div>
        <div>
          <!-- <div v-if="parsedParameters && Object.keys(parsedParameters).length > 0">
    <strong>Parameters:</strong>
    <div v-for="(value, key, index) in parsedParameters" :key="index" class="parameter-item">
      <span>{{ key }}</span>
      <a-input v-model="parsedParameters[key]" :placeholder="'Enter value for ' + key" />
    </div>
  </div>
 -->
          <!-- <a-button @click="addParameter">Add Parameter</a-button> -->
        </div>
        <!-- <strong>Parameters:</strong>
      <div v-for="(value, key, index) in selectedRule.parameters" :key="index" class="parameter-item">
        <a-input v-model="selectedRule.parameters[key]" placeholder="Enter value" />
        <a-input v-model="keys[index]" placeholder="Enter key" @blur="updateKey(index, key)" />
        <a-button type="text" @click="removeParameter(key)" icon="icon-delete" />
      </div>
      <a-button @click="addParameter">Add Parameter</a-button>
    </div> -->

        <div
          ><strong>Priority:</strong>
          <a-input v-model="selectedRule.priority" placeholder="Enter priority"
        /></div>
        <!-- <div><strong>Output Column:</strong> <a-input v-model="selectedRule.output_column" placeholder="Enter output column" /></div> -->

        <div
          ><strong>Output Columns:</strong>
          <div
            v-for="(column, index) in selectedRule.output_column"
            :key="index"
            class="required-column"
          >
            <a-input
              v-model="selectedRule.output_column[index]"
              placeholder="Enter output column "
            />
            <a-button type="text" @click="removeOutputColumn(index)">
              <icon-delete />
            </a-button>
          </div>
          <a-button @click="addOutputColumn">Add Column</a-button>
        </div>

        <!-- 法规 -->
        <div><strong>Regulation Content:</strong></div>
        <a-select
          v-model="selectedRule.regulation_content"
          placeholder="Select Regulation"
          style="width: 100%; margin-bottom: 16px"
        >
          <a-option
            v-for="regulation in regulations"
            :key="regulation.id"
            :value="regulation.content"
          >
            {{ regulation.content }}
          </a-option>
        </a-select>
        <!-- <a-textarea
          v-model="selectedRule.regulation_content"
          placeholder="Regulation Content will be populated automatically"
          rows="4"
          readonly
        /> -->

        <div>
          <div style="display: flex; align-items: center; margin-bottom: 8px">
            <strong>Logic:</strong>
            <a-button
              type="primary"
              size="small"
              style="margin-left: 10px"
              @click="openCopilotModal"
            >
              Rule Copilot
            </a-button>
            <a-button
              type="primary"
              status="success"
              size="small"
              style="margin-left: 10px"
              @click="openRuleGeneratorModal"
            >
              AI Rule Generator
            </a-button>
          </div>
          <a-textarea
            v-model="selectedRule.logic"
            :rows="15"
            style="height: 400px"
          />
        </div>
        <div
          ><strong>Enabled:</strong>
          <a-switch v-model:value="selectedRule.enabled"
        /></div>
      </div>
      <div class="modal-footer">
        <a-space>
          <a-button
            v-if="selectedRule.id !== 0"
            type="primary"
            danger
            @click="handleDelete(selectedRule.id)"
          >
            Delete
          </a-button>
        </a-space>
      </div>
    </a-modal>

    <!-- Rule Copilot Modal -->
    <a-modal
      v-model:visible="isCopilotModalVisible"
      title="Australian Payroll Assistant - AI Copilot"
      :width="800"
      :centered="true"
      :mask-closable="true"
      :closable="true"
      @ok="handleCopilotOk"
      @cancel="handleCopilotCancel"
    >
      <div class="copilot-container">
        <div ref="chatMessagesRef" class="chat-messages">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            :class="['message', message.role]"
          >
            <div class="message-content">
              <div class="message-header">
                <strong>{{
                  message.role === 'user' ? 'You' : 'Payroll Assistant'
                }}</strong>
                <span class="message-time">{{ message.timestamp }}</span>
              </div>
              <div class="message-text">{{ message.content }}</div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <a-textarea
            v-model="userInput"
            placeholder="Ask about Australian payroll rules, regulations, calculations, or any payroll-related questions..."
            :rows="3"
            @keydown.enter.ctrl="sendMessage"
          />
          <div class="input-actions">
            <a-button type="primary" :loading="isLoading" @click="sendMessage">
              Send
            </a-button>
            <a-button @click="clearChat"> Clear Chat </a-button>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- AI Rule Generator Modal -->
    <a-modal
      v-model:visible="isRuleGeneratorModalVisible"
      title="AI Rule Generator"
      :width="800"
      :centered="true"
      :mask-closable="true"
      :closable="true"
      @ok="handleRuleGeneratorOk"
      @cancel="handleRuleGeneratorCancel"
    >
      <div class="rule-generator-container">
        <div class="generator-description">
          <p>Please describe the rule you need, and AI will automatically generate rule data in the correct format:</p>
          <ul>
            <li>Basic Salary Calculation Rules</li>
            <li>Overtime Pay Calculation Rules</li>
            <li>Bonus Calculation Rules</li>
            <li>Allowance Calculation Rules</li>
            <li>Tax Processing Rules</li>
          </ul>
        </div>
        
        <div class="requirement-input">
          <a-textarea
            v-model="ruleRequirement"
            placeholder="Example: Need to set up Australian employee basic salary calculation rules, including basic salary, superannuation and tax deductions"
            :rows="4"
          />
        </div>
        
        <div class="generator-actions">
          <a-button 
            type="primary" 
            :loading="isGenerating" 
            @click="generateRule"
          >
            Generate Rule
          </a-button>
          <a-button @click="clearRequirement">
            Clear
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import axios from 'axios';

  import { ref, defineEmits, computed, onMounted } from 'vue';
  import { queryRulesPresetListNew, RuleRecord } from '@/api/list';
  import useRequest from '@/hooks/request';
  import CardWrap from './card-wrap.vue';
  import baseUrl from '../../../config';

  const emits = defineEmits(['update:selectedRules']);
  const selectedRules = ref<number[]>([]);
  const defaultValue: RuleRecord[] = new Array(6).fill({});
  const { loading, response: renderData } = useRequest<RuleRecord[]>(
    queryRulesPresetListNew,
    defaultValue
  );
  // 存储法规列表
  const regulations = ref<any[]>([]);

  // 存储选择的法规ID
  const selectedRegulationId = ref<number | string>('');
  // 获取法规列表
  async function fetchRegulations() {
    try {
      const response = await axios.get(`${baseUrl}/api/regulations/`);
      if (response.status === 200) {
        console.log('Regulations data:', response.data); // 添加这个 log
        regulations.value = response.data;
      } else {
        console.error('Failed to fetch regulations');
      }
    } catch (error) {
      console.error('Error fetching regulations:', error);
    }
  }

  const isModalVisible = ref(false);
  const isCopilotModalVisible = ref(false);
  const isRuleGeneratorModalVisible = ref(false);
  const userInput = ref('');
  const isLoading = ref(false);
  const isGenerating = ref(false);
  const ruleRequirement = ref('');
  const generatedRule = ref<any>(null);
  const chatMessages = ref<
    Array<{
      role: 'user' | 'assistant';
      content: string;
      timestamp: string;
    }>
  >([]);
  const chatMessagesRef = ref<HTMLElement>();

  const selectedRule = ref<RuleRecord>({
    id: 0,
    name: '',
    category: '',
    comment: '',
    description: '',
    trigger_condition: '',
    required_columns: [] as string[],
    parameters: '',
    priority: '',
    output_column: [] as string[],
    logic: '',
    enabled: false,
    regulation_content: '', // 新增字段
  });
  // 处理法规改变时的逻辑
  function handleRegulationChange(value: string | number) {
    selectedRegulationId.value = value;
    const selectedRegulation = regulations.value.find(
      (reg) => reg.id === value
    );

    if (selectedRegulation) {
      // 自动填充法规内容
      selectedRule.value.regulation_content = selectedRegulation.content;
    } else {
      selectedRule.value.regulation_content = '';
    }
  }
  const selectedRuleId = computed({
    get: () => selectedRule.value.id.toString(),
    set: (value) => {
      selectedRule.value.id = Number(value);
    },
  });

  const parsedParameters = computed(() => {
    try {
      // 将字符串转换为有效的 JSON 字符串
      const jsonString = selectedRule.value.parameters
        .replace(/(\w+):/g, '"$1":')
        .replace(/'/g, '"');
      return JSON.parse(jsonString);
    } catch (error) {
      console.error('Failed to parse parameters:', error);
      return {};
    }
  });

  const industryRules = ref<number[]>([]);
  // const industries = ref<any[]>([]);

  const selectedIndustry = ref<string | number>('all');
  const industries = ref<any[]>([
    { id: 'all', industry_name: 'All Industries', rule_ids: '' }, // Default option
  ]);

  async function fetchIndustries() {
    try {
      const response = await axios.get(
        `${baseUrl}/api/industry?page=1&per_page=10`
      );
      if (response.status === 200) {
        // Maintain the default option and append new industries
        industries.value = [
          { id: 'all', industry_name: 'All Industries', rule_ids: '' },
          ...response.data.results,
        ];
      } else {
        alert(`Failed to fetch industries:`);
      }
    } catch (error) {
      console.error('Error fetching industries:', error);
      alert('Error while fetching industries.');
    }
  }

  async function handleIndustryChange(value: string | number) {
    console.log('handleIndustryChange');
    selectedIndustry.value = value;
    const selected = industries.value.find((industry) => industry.id === value);
    if (selected) {
      industryRules.value = selected.rule_ids.split(',').map(Number);
    } else {
      industryRules.value = [];
    }
  }

  async function fetchRules() {
    const response = await axios.get(`${baseUrl}/api/rules`);
    if (response.status === 200) {
      const sortedData = response.data.data.sort(
        (a, b) => a.priority - b.priority
      );
      console.log(sortedData);
      renderData.value = sortedData;
    } else {
      console.error(`Failed to fetch rules:`);
    }
  }
  async function fetchRules2() {
    const response = await axios.get(`${baseUrl}/api/rules`);
    if (response.status === 200) {
      const sortedData = response.data.sort((a, b) => a.priority - b.priority);
      console.log(sortedData);
      renderData.value = sortedData;
    } else {
      console.error(`Failed to fetch rules:`);
    }
  }

  onMounted(async () => {
    await fetchIndustries();
    await fetchRegulations();
  });

  const layeredRules = computed(() => {
    let rules = [];

    if (selectedIndustry.value === 'all') {
      rules = renderData.value;
    } else {
      const selected = industries.value.find(
        (ind) => ind.id === selectedIndustry.value
      );
      if (selected) {
        const ruleIds = selected.split(',').map(Number);
        rules = renderData.value.filter((rule) => ruleIds.includes(rule.id));
      }
    }

    rules.sort((a, b) => a.priority - b.priority);

    const layers = {};
    rules.forEach((rule) => {
      if (!layers[rule.priority]) {
        layers[rule.priority] = [];
      }
      layers[rule.priority].push(rule);
    });

    return Object.entries(layers).sort((a, b) => Number(a[0]) - Number(b[0]));
  });

  const filteredRules = computed(() => {
    let rules = [];

    if (selectedIndustry.value === 'all') {
      rules = renderData.value;
    } else {
      const selected = industries.value.find(
        (ind) => ind.id === selectedIndustry.value
      );
      if (selected) {
        const ruleIds = selected.rule_ids.split(',').map(Number);
        rules = renderData.value.filter((rule) => ruleIds.includes(rule.id));
      }
    }

    // 在返回之前对规则进行排序
    return rules.sort((a, b) => a.priority - b.priority);
  });

  function handleAddClick() {
    selectedRule.value = {
      id: 0,
      comment: '',
      description: '',
      name: '',
      category: '',
      trigger_condition: '',
      required_columns: [],
      parameters: '',
      priority: '',
      output_column: [],
      logic: '',
      enabled: true,
      regulation_content: '',
    };
    isModalVisible.value = true;
  }

  function handleCardClick(item: RuleRecord) {
    console.log(item);
    selectedRule.value = { ...item };
    isModalVisible.value = true;
  }

  function handleSwitchClick(item: RuleRecord) {
    const index = selectedRules.value.indexOf(item.id);
    if (index === -1) {
      selectedRules.value.push(item.id);
    } else {
      selectedRules.value.splice(index, 1);
    }
    emits('update:selectedRules', [...selectedRules.value]);
  }

  async function handleOk() {
    const method = selectedRule.value.id ? 'PUT' : 'POST';
    const url = selectedRule.value.id
      ? `${baseUrl}/api/rules/${selectedRule.value.id}`
      : `${baseUrl}/api/rules`;

    const requestOptions = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken':
          'k6K6burb3NNevAJProjcDgMmkNltTvW2dawFNx26X0OK4L9DFlZrcbgxGBTwEE06',
        'accept': 'application/json',
      },
      body: JSON.stringify({
        name: selectedRule.value.name,
        category: selectedRule.value.category,
        comment: selectedRule.value.comment,
        description: selectedRule.value.description,
        trigger_condition: selectedRule.value.trigger_condition,
        required_columns: selectedRule.value.required_columns,
        parameters: selectedRule.value.parameters,
        priority: selectedRule.value.priority,
        output_column: selectedRule.value.output_column,
        logic: selectedRule.value.logic,
        enabled: selectedRule.value.enabled,
        regulation_content: selectedRule.value.regulation_content,
      }),
    };

    try {
      const response = await fetch(url, requestOptions);
      console.log(response);
      if (response.ok) {
        alert('Rule saved successfully.');
        // 更新成功后重新加载数据
        await fetchRules2(); // 重新加载最新的规则列表
        isModalVisible.value = false;
        fetchRules(); // Fetch the updated rules list
      } else {
        alert(`Failed to save rule:`);
        alert(response);
      }
    } catch (error) {
      console.error('API Call Error:', error);
      alert('Error while saving rule.');
    }
  }

  async function handleDelete(id: number) {
    try {
      const response = await axios.delete(`${baseUrl}/api/rules/${id}/delete`, {
        headers: {
          'accept': 'application/json',
          'X-CSRFToken':
            'k6K6burb3NNevAJProjcDgMmkNltTvW2dawFNx26X0OK4L9DFlZrcbgxGBTwEE06',
        },
      });
      if (response.status === 200) {
        console.log('Delete response:', response.data);
        await fetchRules(); // Fetch the updated rules list after deletion
        isModalVisible.value = false;
      } else {
        alert(`Failed to delete rule: ${response.statusText}`);
      }
    } catch (error) {
      console.error('Delete error:', error);
      alert('Error while deleting rule.');
    }
  }

  function handleCancel() {
    isModalVisible.value = false;
  }

  // Copilot related functions
  function addMessage(role: 'user' | 'assistant', content: string) {
    // 强制确保 chatMessages.value 是一个数组
    if (!Array.isArray(chatMessages.value)) {
      chatMessages.value = [];
    }
    
    const newMessage = {
      role,
      content,
      timestamp: new Date().toLocaleTimeString(),
    };
    
    chatMessages.value.push(newMessage);
    
    // Scroll to bottom after message is added
    setTimeout(() => {
      if (chatMessagesRef.value) {
        chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
      }
    }, 100);
  }

  function openCopilotModal() {
    isCopilotModalVisible.value = true;
    // Add initial system message
    if (chatMessages.value.length === 0) {
      addMessage(
        'assistant',
        `Hello! I'm your Australian Payroll Assistant. I can help you with:

• Australian payroll rules and regulations
• Salary calculation methods and formulas
• Tax withholding and superannuation calculations
• Overtime and penalty rate calculations
• Leave entitlements and calculations
• Payroll compliance and best practices
• Fair Work Act requirements
• ATO guidelines and requirements

Current rule context:
- Rule Name: ${selectedRule.value.name || 'New Rule'}
- Category: ${selectedRule.value.category || 'Not Set'}
- Regulation Content: ${selectedRule.value.regulation_content || 'Not Set'}

How can I assist you today?`
      );
    }
  }

  async function sendMessage() {
    if (!userInput.value.trim() || isLoading.value) return;

    const userMessage = userInput.value.trim();
    addMessage('user', userMessage);
    userInput.value = '';
    isLoading.value = true;

    try {
      // Call DeepSeek Help API
      const response = await axios.post(
        `${baseUrl}deepseek/help`,
        {
          message: userMessage,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      console.log('Full response:', response);
      
      // 检查响应是否成功（根据你提供的数据结构）
      if (response && response.data && response.data.success === true) {
        // 根据你提供的响应结构，直接获取 message
        const assistantMessage = response.data.message || 'Sorry, I cannot process your request. Please try again.';
        console.log('Assistant message:', assistantMessage);
        addMessage('assistant', assistantMessage);
      } else {
        console.log('Response not successful:', response);
        addMessage(
          'assistant',
          'Sorry, an error occurred while processing your request. Please try again.'
        );
      }
    } catch (error) {
      console.error('DeepSeek API error:', error);
      addMessage(
        'assistant',
        "Sorry, I'm having trouble connecting to my services right now. Please try again later."
      );
    } finally {
      isLoading.value = false;
    }
  }

  function clearChat() {
    chatMessages.value = [];
  }

  function handleCopilotOk() {
    isCopilotModalVisible.value = false;
  }

  function handleCopilotCancel() {
    isCopilotModalVisible.value = false;
  }

  // Rule Generator related functions
  function openRuleGeneratorModal() {
    isRuleGeneratorModalVisible.value = true;
    ruleRequirement.value = '';
    generatedRule.value = null;
  }

  async function generateRule() {
    if (!ruleRequirement.value.trim() || isGenerating.value) return;

    isGenerating.value = true;

    try {
      const response = await axios.post(
        `${baseUrl}deepseek/generate-rule`,
        {
          requirement: ruleRequirement.value.trim(),
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (response && response.data && response.data.success === true) {
        generatedRule.value = response.data.rule_data;
        console.log('Generated rule:', generatedRule.value);
        
        // 直接将生成的规则数据填充到表单中
        selectedRule.value = {
          ...selectedRule.value,
          name: generatedRule.value.name || selectedRule.value.name,
          category: generatedRule.value.category || selectedRule.value.category,
          comment: generatedRule.value.comment || selectedRule.value.comment,
          description: generatedRule.value.description || selectedRule.value.description,
          trigger_condition: generatedRule.value.trigger_condition || selectedRule.value.trigger_condition,
          required_columns: generatedRule.value.required_columns || selectedRule.value.required_columns,
          parameters: generatedRule.value.parameters ? JSON.stringify(generatedRule.value.parameters) : selectedRule.value.parameters,
          priority: generatedRule.value.priority?.toString() || selectedRule.value.priority,
          output_column: generatedRule.value.output_column || selectedRule.value.output_column,
          logic: generatedRule.value.logic || selectedRule.value.logic,
          enabled: generatedRule.value.enabled !== undefined ? generatedRule.value.enabled : selectedRule.value.enabled,
          regulation_content: generatedRule.value.regulation_content || selectedRule.value.regulation_content,
        };
        
        // 关闭弹窗
        isRuleGeneratorModalVisible.value = false;
        
        // 清空输入和生成的规则
        ruleRequirement.value = '';
        generatedRule.value = null;
        
        alert('Rule generated and applied successfully!');
      } else {
        console.error('Failed to generate rule:', response);
        alert('Rule generation failed, please try again.');
      }
    } catch (error) {
      console.error('Rule generation error:', error);
      alert('An error occurred while generating the rule, please try again.');
    } finally {
      isGenerating.value = false;
    }
  }

  function clearRequirement() {
    ruleRequirement.value = '';
    generatedRule.value = null;
  }

  function handleRuleGeneratorOk() {
    // 直接关闭弹窗，规则已经在生成时自动填充
    isRuleGeneratorModalVisible.value = false;
  }

  function handleRuleGeneratorCancel() {
    isRuleGeneratorModalVisible.value = false;
  }

  function addRequiredColumn() {
    selectedRule.value.required_columns.push('');
  }

  function removeRequiredColumn(index: number) {
    selectedRule.value.required_columns.splice(index, 1);
  }

  function addOutputColumn() {
    selectedRule.value.output_column.push('');
  }

  function removeOutputColumn(index: number) {
    selectedRule.value.output_column.splice(index, 1);
  }

  function addParameter(newKey, newValue) {
    console.log('add');
    const currentParams = JSON.parse(
      selectedRule.value.parameters.replace(/(\w+):/g, '"$1":')
    );
    currentParams[newKey] = newValue;
    console.log(currentParams);
    selectedRule.value.parameters = JSON.stringify(currentParams).replace(
      /"(\w+)":/g,
      '$1:'
    );
  }

  function removeParameter(parameters, keys, key) {
    delete parameters[key]; // 使用delete操作符删除对象属性
    const index = keys.indexOf(key);
    if (index > -1) {
      keys.splice(index, 1); // 从键数组中删除键名
    }
  }

  function updateKey(parameters, keys, index, oldKey) {
    const newKey = keys[index];
    if (
      newKey &&
      newKey !== oldKey &&
      Object.prototype.hasOwnProperty.call(parameters, oldKey)
    ) {
      parameters[newKey] = parameters[oldKey]; // 将旧键值赋给新键
      delete parameters[oldKey]; // 删除旧键
      keys[index] = newKey; // 更新键数组中的键名
    }
  }
</script>

<style scoped lang="less">
  .card-wrap {
    height: 100%;
    transition: all 0.3s;
    border: 2px solid var(--color-neutral-3);
    border-radius: 4px;
    font-size: 30px;
    &:hover {
      transform: translateY(-4px);
    }
  }
  .list-wrap {
    padding: 20px;
  }

  .list-row {
    margin-top: 20px;
  }

  .rule-details a-textarea {
    width: 100%;
    min-height: 500px;
  }

  .list-col {
    cursor: pointer;
  }

  .rule-details {
    line-height: 1.5;
    max-height: 70vh;
    overflow-y: auto;
  }

  .rule-details div {
    margin-bottom: 8px;
  }

  .required-column {
    display: flex;
    align-items: center;
  }

  .required-column a-input {
    flex: 1;
  }

  .required-column a-button {
    margin-left: 8px;
  }

  .rule-name {
    font-size: 18px; /* Increased font size for better visibility */
    font-weight: bold;
  }

  /* Copilot Modal Styles */
  .copilot-container {
    display: flex;
    flex-direction: column;
    height: 500px;
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 15px;
    max-height: 350px;
  }

  .message {
    margin-bottom: 15px;
    display: flex;
  }

  .message.user {
    justify-content: flex-end;
  }

  .message.assistant {
    justify-content: flex-start;
  }

  .message-content {
    max-width: 80%;
    padding: 10px 15px;
    border-radius: 12px;
    word-wrap: break-word;
  }

  .message.user .message-content {
    background: #1890ff;
    color: white;
  }

  .message.assistant .message-content {
    background: white;
    border: 1px solid #e8e8e8;
    color: #333;
  }

  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    font-size: 12px;
  }

  .message-time {
    opacity: 0.7;
    font-size: 11px;
  }

  .message-text {
    line-height: 1.4;
    white-space: pre-wrap;
  }

  .chat-input {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .input-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }

  /* Rule Generator Styles */
  .rule-generator-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .generator-description {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    border-left: 4px solid #1890ff;
  }

  .generator-description p {
    margin: 0 0 10px 0;
    font-weight: 500;
  }

  .generator-description ul {
    margin: 0;
    padding-left: 20px;
  }

  .generator-description li {
    margin-bottom: 5px;
    color: #666;
  }

  .requirement-input {
    margin-bottom: 10px;
  }

  .generator-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-start;
  }

  .generated-rule-preview {
    background: #f0f8ff;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #d6e4ff;
  }

  .generated-rule-preview h4 {
    margin: 0 0 15px 0;
    color: #1890ff;
  }

  .rule-preview-content p {
    margin: 5px 0;
    line-height: 1.5;
  }

  .rule-preview-content strong {
    color: #333;
  }
</style>
